<template>
  <div>
    <el-form
      :model="edit_form"
      :rules="edit_rules"
      ref="forgetForms"
      class="w-400px m-auto"
    >
      <el-form-item label="">
        <div>
          <el-upload
            v-model:file-list="imgList"
            accept=".png, .jpg, .jpeg"
            class="mt-20px"
            :before-upload="beforeUpload"
            :on-remove="handleRemove"
            list-type="picture"
          >
            <div class="bg-#bb0615 text-#fff px-20px">点击上传图片</div>
          </el-upload>
        </div>
      </el-form-item>
      <el-form-item prop="name" label="">
        <el-input
          :prefix-icon="User"
          v-model="edit_form.name"
          placeholder="请填写用户名"
        ></el-input>
      </el-form-item>
      <el-form-item>
        <div class="register cursor-pointer" @click="edit">提交</div>
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive } from "vue";
import * as imageConversion from "image-conversion";
import { ElMessage } from "element-plus";
import { edit_rules } from "../data.config";
import { change_name_img } from "@/api/index";
import useUserStore from "@/store/modules/user";

let userStore = useUserStore();
let edit_form = ref({
  name: "",
  headimgurl: "",
});
const imgList = ref([]);

const edit = async () => {
  const { code, message } = await change_name_img(edit_form.value);
  if (code === 200) {
    userStore.get_user_info();
    ElMessage.success("修改成功");
    edit_form.value.name = ""
    edit_form.value.headimgurl = ""
  } else {
    ElMessage.error(message);
  }
};

const toBase64 = (file) => {
  let reader = new FileReader();
  reader.onloadend = function () {
    imgList.value = [];
    edit_form.value.headimgurl = reader.result;
    imgList.value.push({ name: "封面图片", url: edit_form.value.headimgurl });
  };
  if (file) {
    reader.readAsDataURL(file);
  }
};

const beforeUpload = (file) => {
  const isLt2M = file.size / 1024 / 1024 < 2;
  if (!isLt2M) {
    ElMessage.error("上传图片大小不能超过2MB");
    return false;
  } else {
    const isSize = new Promise((resolve, reject) => {
      const _URL = window.URL || window.webkitURL;
      const img = new Image();
      img.onload = () => {
        const valid = true;
        valid ? resolve() : reject();
      };
      img.src = _URL.createObjectURL(file);
    }).then(
      () => {
        return file;
      },
      () => {
        ElMessage.error("上传图片大小不能超过2MB");
        return Promise.reject();
      }
    );
    isSize.then((file) => {
      const isJpgOrPng =
        file.type === "image/jpeg" || file.type === "image/png";
      const isLt2M = file.size / 1024 < 100;
      if (!isJpgOrPng) {
        ElMessage.error("上传图片只能是 JPG 或 PNG 格式!");
        return false;
      }
      return new Promise((resolve) => {
        // 小于100KB 不压缩
        if (isLt2M) {
          resolve(file);
        }
        // 压缩到200KB,这里的200就是要压缩的大小,可自定义
        imageConversion.compressAccurately(file, 50).then((res: any) => {
          toBase64(res);
          resolve(res);
        });
      });
    });
  }
  return false; //取消自动上传
};

const handleRemove = (file) => {
  imgList.value = [];
  edit_form.value.header_img = "";
};
</script>

<style scoped>
.btn:hover {
  background-color: #fcf9f9;
  border-color: #fcf9f9;
  color: #bb0615;
}
.register {
  width: 514px;
  height: 34px;
  background-color: #bb0615;
  border-radius: 22px;
  font-family: MicrosoftYaHei;
  font-size: 18px;
  line-height: 34px;
  letter-spacing: 18px;
  color: #faf5f5;
  text-align: center;
}
</style>
